package com.dmcb.trade.controller;

import com.dmcb.common.business.constants.CommonConstant;

import com.dmcb.common.business.utils.RedisUtils;
import com.dmcb.common.web.controller.BaseController;
import com.dmcb.common.web.conversion.JsonResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 基础爬取类
 * Created by long on 2016/3/14.
 */
public abstract class BaseCrawlerController extends BaseController {

    @Autowired
    private RedisUtils redisUtils;

    /**
     * 爬取文章
     *
     * @param authorId 作者ID
     * @param link     链接
     * @return Json结果
     */
    protected JsonResult crawl(int authorId, String link, boolean monitor, boolean all) {
        if (StringUtils.isBlank(link)) {
            return outputJSONError("链接地址为空");
        }
        // 同步爬取控制
        String key = "concurrent.trade.author." + authorId;
        if (StringUtils.isNotBlank((String)redisUtils.get(key,0))) {
            return outputJSONError("服务器正在同步该作者文章，请稍后...");
        }
        try {
            redisUtils.set(key, "1", 600);
            return call(authorId, link, monitor, all);
        } catch (Exception e) {
            log.error("文章爬取出错", e);
            return outputJSONError(CommonConstant.ABNORMAL_MSG);
        } finally {
            redisUtils.delete(key);
        }
    }

    protected abstract JsonResult call(int authorId, String link, boolean monitor, boolean all) throws Exception;

}
